package com.idea.relax.log.listener;

import com.idea.relax.log.constant.ErrorLogConstant;
import com.idea.relax.log.model.GeneralLogModel;
import com.idea.relax.log.publisher.ILogPublisher;
import com.idea.relax.log.service.IGeneralLogService;
import com.idea.relax.log.service.IRelaxLogService;
import com.idea.relax.log.support.CallbackMessage;
import com.idea.relax.log.support.AppInfoProvider;
import com.idea.relax.log.api.callback.RelaxFailureCallbackHandler;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @className: GeneralLogListener
 * @description: 通用日志事件的监听
 * @author: salad
 * @date: 2022/10/7
 **/
@Slf4j
@AllArgsConstructor
public class GeneralLogWorker implements Runnable {

    private final ILogPublisher.Wrapper<GeneralLogModel> wrapper;

    private final IGeneralLogService generalLogService;

    private final IRelaxLogService relaxLogService;

    private final RelaxFailureCallbackHandler failureCallbackHandler;

    @Override
    public void run() {
        try {
            //存储通用日志
            saveGeneralLog();
        } catch (Exception e) {
            Map<String, Object> data = new HashMap<>(16);
            data.put("source", "GeneralLog");
            data.put(ErrorLogConstant.ERR_LOG_MODEL, wrapper.getValue());
            CallbackMessage message = new CallbackMessage(Thread.currentThread(), e, data);
            failureCallbackHandler.onException(message);
        }
    }

    private void saveGeneralLog() {
        GeneralLogModel model = wrapper.getValue();
        AppInfoProvider.appendServerInfo(model);
        Optional.ofNullable(generalLogService)
                .ifPresent(service -> service.saveGeneralLog(model));
        Optional.ofNullable(relaxLogService)
                .ifPresent(service -> service.saveGeneralLog(model));
    }

}